package com.libservice.cacheservice

import com.libbase.Weak
import com.libbase.cache.CacheInterface
import com.libbase.cache.LevelDBCache
import com.libservice.ServiceManager
import com.libui.BaseApplication
import com.tencent.smtt.sdk.QbSdk
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.addTo

class CacheService :
    CacheServiceInterface {

    override var delegate: CacheServiceDelegate? by Weak()

    override val globalCache: CacheInterface = LevelDBCache(path = null)

    override val globalRemovableCache: CacheInterface = LevelDBCache(path = "R")

    override var userCache: CacheInterface? = null
        private set

    override var userRemovableCache: CacheInterface? = null
        private set

    private var compositeDisposable = CompositeDisposable()

    override fun clearCache(completion: ClearCacheCompletion?) {
        QbSdk.clearAllWebViewCache(BaseApplication.instance, true)

        globalRemovableCache.removeAll()
        userRemovableCache?.removeAll()

        delegate?.clearCache(completion)
    }

    override fun setUserCache() {
        ServiceManager.instance.authService.authRepository.dataObserver
            .subscribe {
                it.value?.userId?.let { userId ->
                    initUserCache(userId)
                } ?: clearUserCache()
            }.addTo(compositeDisposable)

        ServiceManager.instance.authService.authRepository.data?.userId?.let { userId ->
            initUserCache(userId)
        } ?: clearUserCache()
    }

    private fun initUserCache(userId: String) {
        userCache = LevelDBCache(path = userId)
        userRemovableCache = LevelDBCache(path = "R$userId")
    }

    private fun clearUserCache() {
        userCache = null
        userRemovableCache = null
    }
}